/// <reference path="jquery-1.3.2-vsdoc.js"/>
/*

Coded by Nguyen Quang Huy
Y!M: nasavietnam, nasa8x
Email: nasavietnam@gmail.com
Website: www.nasa8x.com
www.vualaptrinh.com
www.nasavietnam.com
www.xomnet.org

*/

(function ($) {
    $.extend({

        Window: {


            focusId: null,
            zIndex: 999999,
            overlayColor: '#000000',
            overlayOpacity: 0.1,
            mainContainer: 'body', // form for asp.net || 'body';
            multiInstant: false,
            options: {},
            defaults: {
                id: null,
                theme: 'office2007blue',
                minWidth: 250,
                minHeight: 100,
                width: 600,
                height: 400,
                _height: null, // store when maxi
                _width: null, // store when maxi
                autoSize: false,
                modal: true,
                ajax: true,
                contentId: null,
                contentClass: null,
                html: '',
                iframe: null,
                url: null,
                status: null,
                title: 'Window title',
                draggable: true,
                resizeable: false,
                close: true,
                closeCallback: null,
                endShowCallback: null,
                maximize: false, // use late
                minimize: false, // use late
                duration: 500,
                isOpen: false,
                position: ['center', 'center']// ['center','top','right','bottom','left']
            },

            _undefined: function () {
                for (var i = 0; i < arguments.length; i++)
                    if (typeof arguments[i] != 'undefined') return false;
                return true;
            },


            _viewport: function () {
                var d = document.documentElement, b = document.body, w = window;
                return jQuery.extend(
                    jQuery.browser.msie ?
                        { left: b.scrollLeft || d.scrollLeft, top: b.scrollTop || d.scrollTop} :
                        { left: w.pageXOffset, top: w.pageYOffset },
                    !this._undefined(w.innerWidth) ?
                        { width: w.innerWidth, height: w.innerHeight} :
                        (!this._undefined(d) && !this._undefined(d.clientWidth) && d.clientWidth != 0 ?
                            { width: d.clientWidth, height: d.clientHeight} :
                            { width: b.clientWidth, height: b.clientHeight }));
            },

            _position: function (pos, _w, _h) {

                var _v = this._viewport();
                pTop = _v.top, pLeft = _v.left, minTop = pTop;

                if ($.inArray(pos, ['center', 'top', 'right', 'bottom', 'left']) >= 0) {
                    pos = [
	                pos == 'right' || pos == 'left' ? pos : 'center',
	                pos == 'top' || pos == 'bottom' ? pos : 'middle'];

                }
                if (pos.constructor != Array) {
                    pos = ['center', 'middle'];
                }
                if (pos[0].constructor == Number) {
                    pLeft += pos[0];
                } else {
                    switch (pos[0]) {
                        case 'left':
                            pLeft += 0;
                            break;
                        case 'right':
                            //pLeft += _v.width - $(this.focusId).outerWidth();
                            pLeft += _v.width - _w;
                            break;
                        default:
                        case 'center':
                            //pLeft += (_v.width - $(this.focusId).outerWidth()) / 2;
                            pLeft += (_v.width - _w) / 2;

                            break;
                    }
                }
                if (pos[1].constructor == Number) {
                    pTop += pos[1];
                } else {
                    switch (pos[1]) {
                        case 'top':
                            pTop += 0;
                            break;
                        case 'bottom':
                            //pTop += _v.height - $(this.focusId).outerHeight();
                            pTop += _v.height - _h;
                            break;
                        default:
                        case 'middle':
                            //pTop += (_v.height - $(this.focusId).outerHeight()) / 2;
                            pTop += (_v.height - _h) / 2;
                    }
                }

                // prevent the dialog from being too high (make sure the titlebar is accessible)

                pTop = Math.max(pTop, minTop);

                return jQuery.extend({ top: pTop, left: pLeft });

            },

            _addAttribute: function (_object, _attrName, _attrValue) {

                var _att = $(_object).attr(_attrName);
                if (_att)
                    $(_object).attr(_attrName, _attrValue + _att);
                else
                    $(_object).attr(_attrName, _attrValue);
            },

            _init: function (options) {
                this.options = jQuery.extend({}, $.Window.defaults, options || {});
                var _id = null;
                if (!this.options.id) {
                    _id = this.options.id = "window_" + new Date().getTime();
                }
                else {
                    _id = this.options.id;

                    if ($('#' + _id)) {
                        alert("Window " + id + " is already registered in the DOM!");
                    }

                };

                this.focusId = '#' + _id;

                /* Window div template
                var _windowHtml =
                '<div id="' + _id + '" class="window ' + this.options.theme + '">' +
                '<div id="' + _id + '_wrapper" class="window-wrapper">' +
                '<div id="' + _id + '_top" class="window-top">' +
                '<div class="windowLeft"></div>' +
                '<div class="windowCenter"></div>' +
                '<div class="windowRight"></div>' +
                '<span id="' + _id + '_title">Window Title</span>' +
                '</div>' +
                '<div id="' + _id + '_middle" class="window-middle">' +
                '<div class="windowLeft"></div>' +
                '<div id="' + _id + '_content" class="window-content">' +               
                '<div id="' + _id + '_loading" class="window-loading"></div>' +
                '</div>' +
                '<div class="windowRight"></div>' +
                '</div>' +

                '<div id="' + _id + '_bottom" class="window-bottom">' +
                '<div class="windowLeft"></div>' +
                '<div class="windowCenter"></div>' +
                '<div class="windowRight"></div>' +
                '<span id="' + _id + '_status">Window Status</span>' +
                '</div>' +

                '<a id="' + _id + '_move" ondblclick="$.Window.maximize()" class="windowMove"></a>' +
                '<a id="' + _id + '_min" class="windowMin" onclick = "$.Window.minimize()" href="javascript:void(0)"></a>' +
                '<a id="' + _id + '_max" class="windowMax" onclick = "$.Window.maximize()" href="javascript:void(0)"></a>' +
                '<a id="' + _id + '_maxed" class="windowMaxed" onclick="$.Window.maximize()" href="javascript:void(0)"></a>' +
                '<a id="' + _id + '_close" class="windowClose" onclick="$.Window.close()" href="javascript:void(0)"></a>' +
                '<a class="windowResize windowResizeN" href="#"></a>' +
                '<a class="windowResize windowResizeS" href="#"></a>' +
                '<a class="windowResize windowResizeW" href="#"></a>' +
                '<a class="windowResize windowResizeE" href="#"></a>' +
                '<a class="windowResize windowResizeNW" href="#"></a>' +
                '<a class="windowResize windowResizeNE" href="#"></a>' +
                '<a class="windowResize windowResizeSW" href="#"></a>' +
                '<a class="windowResize windowResizeSE" href="#"></a>' +

                '</div>' +
                '</div>';
                */

                var _windowHtml =
                     '<div id="' + _id + '" class="window ' + this.options.theme + '">' +
                        '<div id="' + _id + '_wrapper" class="window-wrapper">' +
                            '<table cellpadding="0" cellspacing="0" width="100%">' +
                            '<tr>' +
                                '<td class="window-t-l" id="' + _id + '_left"></td>' +
                                '<td id="' + _id + '_top" class="window-t-m">' +
                                    '<div id="' + _id + '_header" class="window-header">' +
                                        '<a id="' + _id + '_close" class="window-close" href="javascript:void(0)"></a>' +
                                        '<a id="' + _id + '_maxed" class="window-maxed" href="javascript:void(0)"></a>' +
                                        '<a id="' + _id + '_max" class="window-max" href="javascript:void(0)"></a>' +
                                        '<a id="' + _id + '_min" class="window-min" href="javascript:void(0)"></a>' +
                                        '<span class="window-title" id="' + _id + '_title">Window title</span>' +
                                     '</div>' +
                                 '</td>' +
                                 '<td class="window-t-r" id="' + _id + '_right"></td>' +
                            '</tr>' +
                            '<tr>' +
                                '<td class="window-m-l"></td>' +
                                '<td class="window-m-m">' +
                                    '<div id="' + _id + '_loading" class="window-loading"></div>' +
                                    '<div id="' + _id + '_content" class="window-content">' +
                                    '</div>' +
                                '</td>' +
                                '<td class="window-m-r"></td>' +
                             '</tr>' +
                             '<tr>' +
                                '<td class="window-b-l"></td>' +
                                '<td id="' + _id + '_bottom" class="window-b-m">' +
                                    '<div class="window-bottom">' +
                                        '<span id="' + _id + '_status">Window status</span>' +
                                    '</div>' +
                                '</td>' +
                                '<td class="window-b-r"></td>' +
                              '</tr>' +
                            '</table>' +
                        '</div>' +
                   '</div>';

                $(this.mainContainer).append(_windowHtml);

                $('#' + _id + '_wrapper').addClass('window-focus');
                // set Z-Index
                $('.window').css({ zIndex: this.zIndex });
                // Set Widow title
                if (this.options.title) {
                    $('#' + _id + '_title').text(this.options.title);
                };
                // Set Status Bar
                if (this.options.status) {
                    $('#' + _id + '_wrapper').addClass('window-statusbar');
                    $('#' + _id + '_status').text(this.options.status);
                };

                if (this.options.draggable && $.fn.draggable) {
                    $('#' + _id + '_wrapper').addClass('window-movable');
                    $('#' + _id).draggable({ handle: $('#' + _id + '_header'), ghost: true });

                };

                if (this.options.resizeable) {

                    $('#' + _id).resizable();

                };

                // Close
                $('#' + _id + '_close').bind('click', function () {
                    $.Window.close();

                });
                // Minimize
                if (this.options.minimize) {
                    $('#' + _id + '_wrapper').addClass('window-minimizable');
                    $('#' + _id + '_min').bind('click', function () {
                        $.Window.minimize();
                        return false;

                    });


                };
                // Maximize
                if (this.options.maximize) {
                    $('#' + _id + '_wrapper').addClass('window-maximizable');
                    $('#' + _id + '_max').bind('click', function () {
                        $.Window.maximize();
                        return false;
                    });
                    $('#' + _id + '_maxed').bind('click', function () {
                        $.Window.maximize();
                        return false;
                    });

                    $('#' + _id + '_header').bind('dblclick', function () {
                        $.Window.maximize();
                    });
                    $('#' + _id + '_header').bind('click', function () {
                        $.Window.focusId = '#' + _id;
                    });

                };

                if (this.options.iframe) {
                    $('#' + _id + '_content').html('<iframe id="' + _id + '_iframe" frameborder="0"></iframe>');
                };

                if (this.options.contentClass) {
                    $('#' + _id + '_content').addClass(this.options.contentClass);
                };

                $('#' + _id).width(this.options.minWidth);
                $('#' + _id).height(this.options.minHeight);



            },


            _overlay: function (status, callback) {
                switch (status) {
                    case 'show':
                        $("body").append('<div id="window_overlay"></div>');
                        $("#window_overlay").css({
                            position: 'absolute',
                            zIndex: this.zIndex - 1,
                            top: '0px',
                            left: '0px',
                            width: '100%',
                            height: $(document).height(),
                            background: this.overlayColor,
                            opacity: this.overlayOpacity
                        }).fadeIn(500, function () {
                            if ($.isFunction(callback))
                                callback.apply();
                        });
                        break;
                    case 'hide':
                        $('#window_overlay').fadeOut('fast', function () {
                            $("#window_overlay").remove();
                            if ($.isFunction(callback))
                                callback.apply();

                        });

                        break;
                }
            },

            _show: function (callback) {

                var _offset = this._position(this.options.position, this.options.minWidth, this.options.minHeight);

                $(this.focusId).css({ position: 'absolute', zIndex: this.zIndex, left: _offset.left, top: _offset.top })
                .fadeIn(this.options.duration, function () {
                    if ($.isFunction(callback))
                        callback.apply();
                });



            },

            _padding: function () {
                var _h = $(this.focusId + '_top').outerHeight() + $(this.focusId + '_bottom').outerHeight();
                var _w = $(this.focusId + '_left').outerWidth() + $(this.focusId + '_right').outerWidth();

                return jQuery.extend({ h: _h, w: _w });
            },

            loadUrl: function (url, callback) {


                $(this.focusId + '_content').load(url, function () {
                    //$(this.focusId + '_loading').hide();

                    if ($.isFunction(callback))
                        callback.apply();


                });

            },

            loadContent: function (callback) {




                if (this.options.contentId && $('#' + this.options.contentId)) {
                    if ($.isFunction(callback))
                        callback.apply();

                    var _html = this.options.html = $('#' + this.options.contentId).html();

                    //var _html = this.options.html = $('#' + this.options.contentId).clone();

                    $('#' + this.options.contentId).replaceWith('<div id="' + this.options.contentId + '" style="display:none"></div>');

                    $(this.focusId + '_content').html(_html);



                }
                else if (this.options.iframe) {

                    $(this.focusId + '_iframe').attr('src', this.options.url);
                    if ($.isFunction(callback))
                        callback.apply();

                }
                else {
                    this.loadUrl(this.options.url, callback);
                }

            },

            showLoading: function () {

                $($.Window.focusId + '_content').hide();
                $($.Window.focusId + '_loading').fadeIn();

            },
            hideLoading: function () {
                $($.Window.focusId + '_loading').fadeOut(300, function () {
                    $($.Window.focusId + '_content').fadeIn();
                });

            },

            show: function (_options) {
                //close all first


                this._init(_options);

                $.Window.showLoading();

                if (this.options.modal) {
                    this._overlay('show', function () {
                        $.Window._show(function () {
                            $.Window.loadContent(function () {
                                $.Window.hideLoading();
                                $.Window.resize();
                            });
                        });
                    });
                } else {
                    $($.Window.focusId).fadeIn(function () {
                        $.Window._show(function () {
                            $.Window.loadContent(function () {
                                $.Window.hideLoading();
                                $.Window.resize();
                            });
                        });
                    });
                }


            },



            setContentHeight: function () {

                var _p = this._padding();
                var _h = this.options.height - _p.h;
                if (this.options.iframe) {
                    $(this.focusId + '_iframe').height(_h);
                }
                else {
                    $(this.focusId + '_content').height(_h);
                }
            },

            resize: function () {

                var w = this.options.width;
                var h = this.options.height;

                if (this.options.autoSize) {
                    var _padding = this._padding();
                    w = $(this.focusId + '_content').outerWidth() + _padding.w;
                    h = $(this.focusId + '_content').outerHeight() + _padding.h;

                    //alert('H:' + h + ' W:' + w + ' PW:' + _padding.w + ' PH:' + _padding.h + ' outerWidth:' + $(this.focusId + '_content').outerWidth() + ' outerHeight:' + $(this.focusId + '_content').outerHeight());
                }
                else {
                    this.setContentHeight();
                }

                var _offset = this._position(this.options.position, w, h);
                $(this.focusId).animate({ left: _offset.left, top: _offset.top, width: w, height: h }, this.options.duration);

            },

            close: function () {
                //$(this.focusId).animate({ width: 0, height: 0 }, function() {
                $(this.focusId).fadeOut(this.options.duration, function () {
                    $($.Window.focusId).remove();
                    if ($.Window.options.contentId) {

                        $('#' + $.Window.options.contentId).html($.Window.options.html);
                    };

                    if ($.Window.options.modal) {
                        $.Window._overlay('hide');
                    }

                    if ($.isFunction($.Window.options.closeCallback))
                        $.Window.options.closeCallback.apply();

                });
            },

            maximize: function () {
                var w;
                var h;
                if (!$(this.focusId + '_wrapper').hasClass('window-maximized')) {
                    $(this.focusId + '_wrapper').addClass('window-maximized');
                    w = $(window).width() - 20;
                    h = $(window).height() - 20;

                    // save old width & height
                    this.options._width = this.options.width;
                    this.options._height = this.options.height;
                }

                else {
                    w = this.options._width;
                    h = this.options._height;
                    $(this.focusId + '_wrapper').removeClass('window-maximized');
                };

                this.options.height = h;
                this.options.width = w;
                this.resize();

            },

            minimize: function () {
                var h, w, t;


                var status = $(this.focusId + '_content').css("display");
                if (status == 'none') {
                    $(this.focusId + '_content').show();
                    this.resize();

                } else {

                    h = $(this.focusId + '_top').height() + $(this.focusId + '_bottom').height();
                    w = this.options.minWidth;
                    $(this.focusId + '_content').hide();
                    var _v = this._viewport();
                    t = _v.top + _v.height - h;
                    $(this.focusId).animate({ height: h, width: w, left: 5, top: t }, this.options.duration);

                };




            }

            // more prototype



        }// end window


    });

})(jQuery);